package com.own.component.mybatis.injector.method;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.own.component.mybatis.em.SqlMethod;
import com.own.component.mybatis.util.SqlScriptUtil;
import org.apache.ibatis.mapping.MappedStatement;

import java.util.stream.Collectors;

/**
 * UpdateByIdBatch
 *
 * @author chenxueli
 * @date 2020/10/13 15:37
 */
public class UpdateByIdBatch extends AbstractMethod {

    public UpdateByIdBatch() {
        super("updateByIdBatch");
    }

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        var method = SqlMethod.UPDATE_ID_BATCH;
        var setScript = "<set>" + tableInfo.getFieldList().stream().map(field -> SqlScriptUtil.convertForeach(" when #{item." + tableInfo.getKeyProperty() + "} then #{item." + field.getProperty() + "} ", "list", null, "item", " ", field.getColumn() + " = case " + tableInfo.getKeyColumn(), " end,")).collect(Collectors.joining(" ")) + "</set>";
        var whereScript = tableInfo.getKeyColumn() + " in " + SqlScriptUtil.convertForeach("#{item." + tableInfo.getKeyProperty() + "} ", "list", null, "item", ",", "(", ")");
        var sql = String.format(method.getSql(), tableInfo.getTableName(), setScript, whereScript);
        var sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, modelClass);
        return this.addUpdateMappedStatement(mapperClass, modelClass, method.getMethod(), sqlSource);
    }

}
